﻿using System;
using System.Threading;
using System.Threading.Tasks;

namespace InDepth2Demo.Chapter15
{
    internal class AwaiterDemo
    {
        public static void Call()
        {
            Console.WriteLine("我是主线程，线程ID：" + Thread.CurrentThread.ManagedThreadId);

            Console.WriteLine("---------------------------------");

            Console.WriteLine("1 我是主线程，线程ID：{0}", Thread.CurrentThread.ManagedThreadId);

            var testResult = TestAsync();

            testResult.GetAwaiter().OnCompleted(() =>
            {
                var id = testResult.Id;
                Console.WriteLine("My name is: " + id);
            });

            Console.WriteLine("");
            TestAsync1();

            Console.WriteLine("主线程执行完毕");

            Console.ReadKey();
        }

        static async Task TestAsync()
        {
            Console.WriteLine("2 调用GetReturnResult()之前，线程ID：{0}。当前时间：{1}", Thread.CurrentThread.ManagedThreadId,
                DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
            var name = GetReturnResult();

            Console.WriteLine("4 调用GetReturnResult()之后，线程ID：{0}。当前时间：{1}", Thread.CurrentThread.ManagedThreadId,
                DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));

            Console.WriteLine("6 得到GetReturnResult()方法的结果一：{0}。当前时间：{1}", await name,
                DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
            Console.WriteLine("6 得到GetReturnResult()方法的结果二：{0}。当前时间：{1}", name.GetAwaiter().GetResult(),
                DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
        }

        static async Task<string> GetReturnResult()
        {
            Console.WriteLine("3 执行Task.Run之前, 线程ID：{0}", Thread.CurrentThread.ManagedThreadId);

            return await Task.Run(() =>
            {
                Thread.Sleep(20000);
                Console.WriteLine("5 GetReturnResult()方法里面线程ID: {0}", Thread.CurrentThread.ManagedThreadId);
                return "我是返回值";
            });
        }

        static async void TestAsync1()
        {
            Console.WriteLine("Test 线程ID：" + Thread.CurrentThread.ManagedThreadId);
            await Task.Run(() =>
            {
                Thread.Sleep(5000);
                Console.WriteLine("Test方法等待5秒开始执行");
            });
            Console.WriteLine("Test 线程ID：" + Thread.CurrentThread.ManagedThreadId);
        }
    }
}
